/* #backup_put pathname */
#include <unistd.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <kvs.h>

#include "defines.h"

extern char** environ;
int myfunc(char* pathname);

char global_pathname[PATHNAME_LEN];
char buffer[BUFFER_SIZE];

int main(int argc, char** argv)
{
	int size_in_G;
	KVS_SET kvs;
	FILE* fp=NULL;
	char disk_pathname[PATHNAME_LEN], init_dir[PATHNAME_LEN];
	
/* parse command line. */
/* directory, index_file */
	if (argc!=2)
	{
		printf ("usage: pathname.\n");
		return 1;
	}

	memset(init_dir, 0, sizeof(init_dir));
	memset(disk_pathname, 0, sizeof(disk_pathname));
	memset(global_pathname, 0, sizeof(global_pathname));

	if ( strlen(argv[1])>=PATHNAME_LEN) 
	{
		printf ("too long:%s \n", argv[1]);
		return 1;
	}
	sscanf(argv[1], "%s", init_dir);

/* read from backup.conf */
	fp=fopen("backup.conf","r");	
	if (fp==NULL)
	{
		printf ("%s open failed.\n", "backup.conf");
		return 1;
	}
	fscanf(fp, "%d", &size_in_G);
	fscanf (fp, "%s\n", disk_pathname);
	fclose(fp);
	printf ("size:%d  disk_pathname:%s\n", size_in_G, disk_pathname);

	
/* init KVS_SET */
	kvs.init_type=KVS_LOAD;
	kvs.size_in_g=size_in_G;
	strcpy(kvs.disk_file, disk_pathname);
	strcpy(kvs.log, "/tmp/kvs.log");
	strcpy(kvs.disk_log, "/tmp/kvs_disk.log");
	strcpy(kvs.sync_log, "/tmp/kvs_sync.log");
	strcpy(kvs.index_log, "/tmp/kvs_index.log");

	kv_init_2(&kvs);

	path_abs(global_pathname, init_dir);
	printf ("init path: [%s]\n", global_pathname);

/* kv_put (global_pathname) */
	myfunc(global_pathname);
	
	kv_exit();

	return 0;
}


/* char buffer[5*1024*1024]; */
/* FILE* fp_index=NULL; */
int myfunc(char* pathname)
{
	int fd,n,total, state;
	char* ptr;

	memset(buffer, 0, sizeof(buffer));

	/* read(pathname) --> buffer[] */
	fd=open(pathname, O_RDONLY);
	if (fd<0)
	{
		printf ("open error: %s\n", pathname);
		return 1;
	}

	ptr=buffer;
	total=0;
	while ( (n=read(fd, ptr, BUFFER_SIZE-total)) > 0 ) 
	{
		total+=n;
		ptr+=n;
		if (BUFFER_SIZE-total<=0)
		{
			printf ("out of limit, size:%s\n",pathname);
			return 1;
		}
	}
	if (n==-1)
	{
		printf ("read error.\n");
		return 1;
	}
		
	/* kvs_put (pathname, buffer[]) */
	printf ("kvs put: %s, buffer_size:%d\n", pathname, total);
	fflush(stdout);
	state=kv_put(pathname, strlen(pathname), buffer, total);
	if (state==KV_PUT_FAIL)
	{
		printf ("kvs put fail: %s, buffer_size:%d\n", pathname, total);
		return 1;
	}

	close(fd);
	return 0;
}

